package dao

import (
	"context"
	"fmt"
	"gitee.com/hxchjm/go-admin/internal/models"
	"gitee.com/hxchjm/go-admin/pkg/db"
	"gitee.com/hxchjm/go-admin/pkg/permit"
	"github.com/hxchjm/log"
	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type SysApi struct {
	models.SysApi
}

//func (SysApi) TableName() string {
//	return "sys_api"
//}

// GetPage 获取SysApi列表
func (e SysApi) GetPage(ctx context.Context, req *models.ReqApiGetPage) ([]models.SysApi, int64, error) {
	if req.Size <= 0 {
		req.Size = 20
	}
	_ = copier.Copy(&e, req)
	var count int64

	var list []models.SysApi
	if err := db.GetDB().Debug().Model(&e).Scopes(WithCondition(*req), permit.DataScope(ctx)).Limit(req.Size).Offset((req.Page - 1) * req.Size).
		Find(&list).Error; err != nil {
		log.Errorf(ctx, "SysApi GetPage err(%+v)", err)
		return nil, 0, err
	}
	_ = db.GetDB().Debug().Model(&e).Where(e).Count(&count).Error

	return list, count, nil
}

// Get 获取SysApi对象with id
func (e SysApi) Get(ctx context.Context) (*models.SysApi, error) {
	var data models.SysApi
	err := db.GetDB().Model(&data).First(&data, e.Id).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		log.Errorf(ctx, "Service Get error:%s", err)
		return nil, err
	}
	if err != nil {
		log.Errorf(ctx, "db error:%+v", err)
		return nil, err
	}
	return &data, nil
}

// Update 修改SysApi对象
func (e SysApi) Update(ctx context.Context) error {
	var model = models.SysApi{}
	tx := db.GetDB().Debug().First(&model, e.Id)
	if tx.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	_ = copier.CopyWithOption(&model, e, copier.Option{IgnoreEmpty: true})
	if err := tx.Save(&model).Error; err != nil {
		log.Errorf(ctx, "Service UpdateSysApi error:%s", err)
		return err
	}

	return nil
}

// Delete 删除SysApi
func (e SysApi) Delete(ctx context.Context, ids []int) error {
	if len(ids) <= 0 {
		return nil
	}
	var data models.SysApi
	d := db.GetDB().Model(&data).Delete(&data, ids)
	if err := d.Error; err != nil {
		log.Errorf(ctx, "Service RemoveSysApi error:%s", err)
		return err
	}
	if d.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// CheckStorageSysApi 创建SysApi对象
func (e SysApi) CheckStorageSysApi(ctx context.Context, r *[]models.Router) error {
	for _, v := range *r {
		err := db.GetDB().Debug().Where(models.SysApi{Path: v.RelativePath, Action: v.HttpMethod}).
			Attrs(models.SysApi{Handle: v.Handler}).
			FirstOrCreate(&models.SysApi{}).Error
		if err != nil {
			log.Errorf(ctx, "CheckStorageSysApi err (%+v)", err)
			err = fmt.Errorf("Service CheckStorageSysApi error: %s ", err.Error())
			return err
		}
	}
	return nil
}
